﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Reflection;
using System.Collections.Generic;

class test
{
    public string joke()
    {
        return "No joke";
    }
    public string hw()
    {
        return "Hello, World!";
    }
}

class MyTcpListener
{
    public static void Main()
    {
        TcpListener server = null;
        server = new TcpListener(13000);

        server.Start();


        Byte[] bytes = new Byte[256];
        String data = null;


        while (true)
        {
            Console.WriteLine("Ожидание соединения... ");


            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Есть соединение!");

            data = null;


            NetworkStream stream = client.GetStream();

            int i;


            while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                test t = new test();
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Принято: {0}", data);

                string a;
                if ((string.Compare(data, "hw") == 0) || (string.Compare(data, "joke") == 0))
                {
                    a = (string)t.GetType().InvokeMember(data, BindingFlags.InvokeMethod, null, t, null);
                }
                else
                {
                    a = "Неизвестный метод";
                }

                byte[] msg = System.Text.Encoding.ASCII.GetBytes(a);


                stream.Write(msg, 0, msg.Length);
                Console.WriteLine("Отправлено: {0}", a);
            }


            client.Close();
        }
    }
}
